package com.citycloud.ccuap.tc.admin.projectfunction;

import com.citycloud.ccuap.commons.constants.GlobalOperateType;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.web.session.CurrentUser;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.util.StringUtil;
import com.citycloud.ccuap.tc.admin.entity.SysProjectFunction;
import com.citycloud.ccuap.tc.admin.repository.SysProjectFunctionRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.springframework.data.domain.Sort.Direction.DESC;

/**
 * projectId 和 funId确定菜单唯一性
 */
@Api("项目（站点）菜单")
@RestController
@RequestMapping("/v1/yq/projectfunction")
public class ProjectFunctionController extends BaseController {
	@Autowired
    private IProjectFunctionService projectFunctionService;

	@Autowired
	private SysProjectFunctionRepository sysProjectFunctionRepository;
	
	/**
	 * 默认构造函数
	 */
	public ProjectFunctionController() {
	}

	@ApiOperation("根据主键获取对象")
	@RequestMapping(value = "/findById", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findById() throws Exception {
		String prjFunId = getStringParameter("prjFunId");
		SysProjectFunction sysProjectFunction = projectFunctionService.findById(prjFunId);
		
		JSONData jsonData = new JSONData(sysProjectFunction);
		return jsonData;
	}
	
	/**
	 * 获取页面提交的对象
	 * 
	 * @return struts result
	 * @throws Exception
	 */
	private SysProjectFunction getRequestDataObject(short operateType) throws Exception {
		SysProjectFunction sysProjectFunction = new SysProjectFunction();
		ResolveRequest.fillData(request, sysProjectFunction);

		if (GlobalOperateType.ADD == operateType) {
		} else if (GlobalOperateType.EDIT == operateType) {
		}

		return sysProjectFunction;
	}
	
	@ApiOperation("新增对象")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public JSONData add() throws Exception {
		SysProjectFunction sysProjectFunction = getRequestDataObject(GlobalOperateType.ADD);
//		AppAssert.isNull(sysProjectFunctionRepository.findByFunIdAndProjectId(sysProjectFunction.getFunId(), sysProjectFunction.getProjectId()), "菜单编码已存在！");
//		AppAssert.isTrue(!sysProjectFunction.getFunId().equals(sysProjectFunction.getPid()), "当前菜单不能与上级菜单相同！");
		sysProjectFunction.setFunId(UUID.randomUUID().toString().replace("-", "")+"_"+sysProjectFunction.getProjectId());
		projectFunctionService.insert(sysProjectFunction);

		JSONData jsonData = new JSONData("添加项目（站点）菜单成功！");
		return jsonData;
	}

	@ApiOperation("菜单导入")
	@RequestMapping({"/importProjectFunction"})
	public JSONData importProjectFunction(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		String reqProjectId = multipartRequest.getParameter("projectId");

		Long projectId;
		if (StringUtils.isNotBlank(reqProjectId)) {
			projectId = Long.valueOf(reqProjectId);
		} else {
			projectId = getProjectId();
		}
		AppAssert.notNull(projectId, "用户信息已过期");

		try {
			InputStream is = file.getInputStream();
			projectFunctionService.importProjectFunction(is,projectId);
		}catch(Exception e){
			return new JSONData(false,e.getMessage());
		}
		return new JSONData("导入成功！");
	}

	@ApiOperation("更新对象")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public JSONData update() throws Exception {
		SysProjectFunction sysProjectFunction = getRequestDataObject(GlobalOperateType.EDIT);

//		AppAssert.isTrue(!sysProjectFunction.getFunId().equals(sysProjectFunction.getPid()), "当前菜单不能与上级菜单相同！");
		SysProjectFunction existSysFunction = sysProjectFunctionRepository.findByFunIdAndProjectId(sysProjectFunction.getFunId(), sysProjectFunction.getProjectId());
		Assert.notNull(existSysFunction, "查询站点菜单为空！");
		String existFullPath = existSysFunction.getFullPath();
		String fullPath = sysProjectFunction.getFullPath();
		if (!existFullPath.equals(fullPath)) {
			//批量修改全路径
			projectFunctionService.updateFullPathBatch(sysProjectFunction.getProjectId(), sysProjectFunction.getFunId(), existFullPath, fullPath);
		}
		projectFunctionService.update(sysProjectFunction);

		JSONData jsonData = new JSONData("修改项目（站点）菜单成功！");
		return jsonData;
	}
	

	@ApiOperation("删除对象")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public JSONData delete() throws Exception {
		String prjFunId = getStringParameter("prjFunId");
		projectFunctionService.deleteById(prjFunId);
		
		JSONData jsonData = new JSONData("删除项目（站点）菜单成功！");
		return jsonData;
	}
	
	@ApiOperation("删除多个对象")
	@RequestMapping(value = "/deleteList", method = RequestMethod.POST)
	public JSONData deleteList() throws Exception {
		String prjFunIds = getStringParameter("prjFunIds");
		List<String> prjFunIdList = StringUtil.strToStringList(prjFunIds);
		
		projectFunctionService.deleteIdList(prjFunIdList);
		
		JSONData jsonData = new JSONData("删除项目（站点）菜单成功！");
		return jsonData;
	}

	@ApiOperation("根据条件查询对象")
	@RequestMapping(value = "/query", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData query() throws Exception {
		PageQuery<SysProjectFunction> pageQuery = ResolveRequest.getPageForParams(request);
		SysProjectFunctionDTO sysProjectFunctionDTO = new SysProjectFunctionDTO();
		ResolveRequest.fillData(request, sysProjectFunctionDTO, "q_", true);

		Sort sort = Sort.by(DESC, "prjFunId");
//		Sort sort = new Sort(DESC, "prjFunId");
		pageQuery.setSort(sort);
		
		
		PageQuery<SysProjectFunction> pageData = projectFunctionService.selectPage(pageQuery, sysProjectFunctionDTO);
		
		JSONData jsonData = new JSONData(pageData);
		return jsonData;
	}

	@ApiOperation("查找树节点")
	@RequestMapping(value = "/findNextChildNodeTree", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findNextChildNodeTree() throws Exception {
		Long projectId = getLongParameter("projectId");
		Assert.notNull(projectId, "站点不能为空！");
		String pid;
		String node = request.getParameter("node");
		if (node == null || "".equals(node) || "-1".equals(node)) {
			pid = null;
		} else {
			pid = String.valueOf(node);
		}

		List<TreeNode> treeNodeList;
		String funName = request.getParameter("nodeName");
		if (StringUtils.isBlank(funName)) {
			treeNodeList = projectFunctionService.findNextChildNodeTree(pid, projectId);
		} else {
			treeNodeList = projectFunctionService.findNodeTreeByName(funName, projectId);
		}

		JSONData jsonData = new JSONData(treeNodeList);
		return jsonData;
	}

	@ApiOperation("删除节点")
	@RequestMapping(value = "/deleteNode", method = RequestMethod.POST)
	public JSONData deleteNode() throws Exception {
		Long projectId = getLongParameter("projectId");
		String funId = getStringParameter("funId");
		projectFunctionService.deleteNode(projectId, funId);

		JSONData jsonData = new JSONData("删除项目（站点）菜单节点成功！");
		return jsonData;
	}

	@ApiOperation("删除多个节点")
	@RequestMapping(value = "/deleteNodeList", method = RequestMethod.POST)
	public JSONData deleteNodeList() throws Exception {
		Long projectId = getLongParameter("projectId");
		String funIds = getStringParameter("funIds");
		List<String> funIdList = StringUtil.strToStringList(funIds);
		projectFunctionService.deleteNodeList(projectId, funIdList);

		JSONData jsonData = new JSONData("删除项目（站点）菜单节点成功！");
		return jsonData;
	}

	@ApiOperation("根据功能编号和项目编号获取对象")
	@RequestMapping(value = "/findByFunIdAndProjectId", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findByFunIdAndProjectId() throws Exception {
		String funId = getStringParameter("funId");
		Long projectId = getLongParameter("projectId");
		SysProjectFunction sysProjectFunction = sysProjectFunctionRepository.findByFunIdAndProjectId(funId, projectId);

		JSONData jsonData = new JSONData(sysProjectFunction);
		return jsonData;
	}

	@ApiOperation("根据id查找名称")
	@RequestMapping(value = "/findFunName", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findFunName() throws Exception {
		String funId = getStringParameter("funId");
		Long projectId = getLongParameter("projectId");

		SysProjectFunction function = sysProjectFunctionRepository.findByFunIdAndProjectId(funId, projectId);
		AppAssert.notNull(function, "查询站点菜单对象为空！");

		JSONData jsonData = new JSONData("查询成功！");
		jsonData.setData(function.getFunName());
		return jsonData;
	}

	@ApiOperation("获取当前用户站点菜单地址列表")
	@RequestMapping(value = "/findAllLocationByProject", method = {RequestMethod.GET, RequestMethod.POST})
	public JSONData findAllLocationByProject() throws Exception {
		CurrentUser user = super.getCurrentUser();
		Long projectId = user.getProject().getProjectId();
		AppAssert.notNull(projectId, "当前用户非站点用户！");

		List<SysProjectFunction> functionList = sysProjectFunctionRepository.findByProjectIdOrderByOrderNo(projectId);

		List<String> list = new ArrayList<>();
		for (SysProjectFunction projectFunction : functionList) {
			list.add(projectFunction.getLocation());
		}
		JSONData jsonData = new JSONData(list);
		return jsonData;
	}
}